package cn.swu.lyx.homework2

import android.view.LayoutInflater
import android.view.TextureView
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView

class CommodityAdapter(val commodity:ArrayList<commodity>):RecyclerView.Adapter<CommodityAdapter.CommodityViewHolder>(){
    //ViewHolder是为了对控件实例进行缓存 就不需要每次都通过findViewById来获取控件实例
    inner class CommodityViewHolder(itemView: View):RecyclerView.ViewHolder(itemView){
        //俩种写法
        val name:TextView=itemView.findViewById(R.id.cname)
        val description=itemView.findViewById<TextView>(R.id.cdescription)
        val img:ImageView=itemView.findViewById(R.id.cimage)
    }

    //加载布局 创建ViewHolder实例
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CommodityViewHolder {
        val view=LayoutInflater.from(parent.context).inflate(R.layout.item_commodity,parent,false)
        return CommodityViewHolder(view)
    }

    //对子项赋值，每个子项滚动到屏幕上时执行，position是得到当前Commodity实例再将其相关信息设置到CommodityViewHolder的TextView和imageView
    override fun onBindViewHolder(holder: CommodityViewHolder, position: Int) {
        val commodity=commodity[position]
        holder.name.text=commodity.name
        holder.description.text=commodity.description
        holder.img.setImageResource((commodity.image))
    }

    //告诉RecycleView到底有多少子项
    override fun getItemCount(): Int {
        return commodity.size
    }
}